﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;


namespace Common
{
    public class WebUtility
    {
        public static void Print(string str)
        {
            HttpContext.Current.Response.Write(str.ToString());
            HttpContext.Current.Response.End();
        }

        public static void Response(string str)
        {
            HttpContext.Current.Response.Write(str.ToString());
        }

        public static void JsAlertToGo(string text,string url)
        {
            HttpContext.Current.Response.Write("<script>alert('" + text + "')</script>");
            HttpContext.Current.Response.Write("<script>document.location='" + url + "'</script>");
        }

        public static void JsAlertToBack(string text)
        {
            HttpContext.Current.Response.Write("<script>alert('" + text + "')</script>");
            HttpContext.Current.Response.Write("<script>window.history.back();</script>");
        }

        public static void JsAlertToParent(string text, string url)
        {
            HttpContext.Current.Response.Write("<script>alert('" + text + "');parent.window.location.href='" + url + "'</script>");
            HttpContext.Current.Response.End();
        }

        public static void JsAlertToIframe(string text)
        {
            HttpContext.Current.Response.Write("<script>alert('" + text + "');");
            HttpContext.Current.Response.Write("parent.window.document.getElementById('iframe1').src='Business_In.aspx?menutype=121&type=1';");
            HttpContext.Current.Response.Write("parent.window.document.getElementById('iframe2').src='Business_In.aspx?menutype=121&type=2';");
            HttpContext.Current.Response.Write("parent.window.document.getElementById('iframe3').src='Business_In.aspx?menutype=121&type=4';");
            HttpContext.Current.Response.Write("parent.window.document.getElementById('iframe4').src='Business_In.aspx?menutype=121&type=5';");
            HttpContext.Current.Response.Write("parent.tb_remove();</script>");
            HttpContext.Current.Response.End();
        }

        public static string DateTimeToShort(object datetime)
        {
            if (datetime == null)
                return "";
            else
                if (datetime.ToString().Length > 0)
                    return Convert.ToDateTime(datetime).ToString("yyyy-MM-dd HH:mm").Replace("-","/");
                else
                    return "";
        }

        public static string DateTimeToString(object datetime)
        {
            if (datetime == null)
                return "";
            else
                if (datetime.ToString().Length > 0)
                    return Convert.ToDateTime(datetime).ToString("yyyy-MM-dd HH:mm:ss").Replace("-", "/");
                else
                    return "";
        }

        public static string DecimalToString(Decimal? price)
        {
            if (price.HasValue)
                return price.Value.ToString();
            else
                return "";
        }

        public static string NullDecimalToString(object obj)
        {
            if (obj.ToString() == "0")
                return "";
            else
                return obj.ToString();
        }

        public static decimal DecimalToDecimal(Decimal? price)
        {
            if (price.HasValue)
                return Convert.ToDecimal(price);
            else
                return 0;
        }

        public static string DateTimeToString(DateTime? datetime)
        {
            if (datetime.HasValue)
                return datetime.Value.ToString();
            else
                return "";
        }

        public static string DateTimeToShortString(object datetime)
        {
            if (datetime!=null)
                return Convert.ToDateTime(datetime).ToString("yyyy-MM-dd");
            else
                return "";
        }

        public static int IntToInt(int? num)
        {
            if (num.HasValue)
                return Convert.ToInt32(num);
            else
                return 0;
        }


        public static int GetTimeSpanD(DateTime StartTime, DateTime EndTime)
        {
            try
            {
                TimeSpan ts = EndTime - StartTime;
                return ts.Days;
            }
            catch (Exception ex)
            {
                return 0;
            }
        }

        public static int GetTimeSpanH(DateTime StartTime, DateTime EndTime)
        {
            try
            {
                TimeSpan ts = EndTime - StartTime;
                return ts.Hours;
            }
            catch (Exception ex)
            {
                return 0;
            }
        }

        public static string GetTimeSpanH(object StartTime, object EndTime)
        {
            if (StartTime == null || EndTime == null)
                return "";
            else
            {
                try
                {
                    TimeSpan ts = Convert.ToDateTime(EndTime) - Convert.ToDateTime(StartTime);
                    return ts.Hours.ToString() + "小时";
                }
                catch (Exception ex)
                {
                    return "";
                }
            }
        }

        public static int GetTimeSpanM(DateTime StartTime, DateTime EndTime)
        {
            try
            {
                TimeSpan ts = EndTime - StartTime;
                return ts.Minutes;
            }
            catch (Exception ex)
            {
                return 0;
            }
        }

        public static string GetTimeSpanM(object StartTime, object EndTime)
        {
            if (StartTime == null || EndTime == null)
                return "";
            else
            {
                try
                {
                    TimeSpan ts = Convert.ToDateTime(EndTime) - Convert.ToDateTime(StartTime);
                    return ts.Minutes.ToString() + "分";
                }
                catch (Exception ex)
                {
                    return "";
                }
            }
        }

        public static string GetRequestString(string QueryName)
        {
            if (string.IsNullOrEmpty(HttpContext.Current.Request[QueryName]))
                return "";
            else
                return HttpContext.Current.Request[QueryName].ToString();
        }

        //-------------------------------------------Pager---------
        public static int GetTotalPage(int TotalRowCount,int PageSize)
        {
            if ( TotalRowCount % PageSize == 0 )
                return TotalRowCount/PageSize;
            else
                return TotalRowCount/PageSize + 1;
        }

        public static int GetCurrentPage(int StartRowIndex ,int PageSize)
        {
            return StartRowIndex / PageSize + 1;
        }

        public static string MD5(string md5str, int type)
        {
            if (type == 16)
            {
                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(md5str, "MD5").Substring(8, 16).ToLower();
            }
            else if (type == 32)
            {
                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(md5str, "MD5").ToLower();
            }
            return "";
        }

        public static bool Backup()
        {
            string filename = DateTime.Now.ToString("yyyyMMddhhmmss");
            string path = HttpContext.Current.Server.MapPath("../") + "\\Backup\\" + filename + ".bak";
            string backupstr = "backup database [CIM.Net] to disk='" + path + "';";

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CIM"].ToString());
            SqlCommand cmd = new SqlCommand(backupstr, conn);
            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();

                string sql = "Insert into Sys_BackupLog(FileName,Status,CreateTime,UserKey) Values(";
                sql += "'"+filename+".bak',";
                sql += "'1',";
                sql += "'"+DateTime.Now.ToString()+"',";
                sql += "'"+HttpContext.Current.Session["UserKey"].ToString()+"')";
                cmd = new SqlCommand(sql,conn);
                cmd.ExecuteNonQuery();
                
                return true;
            }
            catch(Exception ex)
            {
                string sql = "Insert into Sys_BackupLog(FileName,Status,CreateTime,UserKey) Values(";
                sql += "'',";
                sql += "'0',";
                sql += "'" + DateTime.Now.ToString() + "',";
                sql += "'" + HttpContext.Current.Session["UserKey"].ToString() + "')";
                cmd = new SqlCommand(sql, conn);
                cmd.ExecuteNonQuery();

                WebUtility.Print(ex.Message);
                return false;
            }
            finally
            {
                
                conn.Close();
            }
        }

        public static bool Restore(string FileName)
        {
            string path = HttpContext.Current.Server.MapPath("../") + "\\Backup\\" + FileName + ".bak";
            string backupstr = "restore database [CIM.Net] from disk='" + path + "';";

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CIM"].ToString());
            SqlCommand cmd = new SqlCommand(backupstr, conn);
            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();

                string sql = "Insert into Sys_RestoreLog(FileName,Status,CreateTime,UserKey) Values(";
                sql += "'" + FileName + ".bak',";
                sql += "'1',";
                sql += "'" + DateTime.Now.ToString() + "',";
                sql += "'" + HttpContext.Current.Session["UserKey"].ToString() + "')";
                cmd = new SqlCommand(sql, conn);
                cmd.ExecuteNonQuery();

                return true;
            }
            catch (Exception ex)
            {
                string sql = "Insert into Sys_RestoreLog(FileName,Status,CreateTime,UserKey) Values(";
                sql += "'" + FileName + ".bak',";
                sql += "'0',";
                sql += "'" + DateTime.Now.ToString() + "',";
                sql += "'" + HttpContext.Current.Session["UserKey"].ToString() + "')";
                cmd = new SqlCommand(sql, conn);
                cmd.ExecuteNonQuery();

                WebUtility.Print(ex.Message);
                return false;
            }
            finally
            {

                conn.Close();
            }
        }

        //删除文件
        public static void DelUploadFile(string FilePath)
        {
            FileInfo info = new FileInfo(FilePath);
            if (info.Exists)
            {
                info.Delete();
            }
        }
       
        public static string GetTitleByMenu(string MenuType)
        {
            string Title = "";

            //---------------业务管理开始Begin------------
            switch (MenuType.Substring(0, 2))
            {
                case "11":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                Title = "在线预约 >> 我要预约";
                                break;
                            case "2":
                                Title = "在线预约 >> 预约历史";
                                break;
                            case "3":
                                Title = "在线预约 >> 预约查询";
                                break;
                        }
                        break;
                    }
                case "12":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                Title = "预约状态 >> 未完成";
                                break;
                            case "2":
                                Title = "预约状态 >> 已完成";
                                break;
                            case "3":
                                Title = "预约状态 >> 预约查询";
                                break;
                        }
                        break;
                    }
                case "13":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                Title = "预约管理 >> 添加预约";
                                break;
                            case "3":
                                Title = "预约管理 >> 任务处理";
                                break;
                            case "4":
                                Title = "预约管理 >> 预约查询";
                                break;
                        }
                        break;
                    }
                case "14":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                Title = "技术处理 >> 添加服务内容";
                                break;
                            case "2":
                                Title = "技术处理 >> 服务内容管理";
                                break;
                        }
                    }
                    break;

            }
            //---------------业务管理开始End------------

            //-------------------------员工管理Begin-------------------------
            switch (MenuType.Substring(0, 2))
            {
                case "21":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                Title = "考核管理 >> 预约服务";
                                break;
                            case "2":
                                Title = "考核管理 >> 服务回访";
                                break;
                        }
                        break;
                    }
                case "22":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                if (!string.IsNullOrEmpty(HttpContext.Current.Request["KqKey"]))
                                    Title = "考勤管理 >> 修改考勤";
                                else
                                    Title = "考勤管理 >> 添加考勤";
                                break;
                            case "2":
                                Title = "考勤管理 >> 考勤管理";
                                break;
                            case "3":
                                Title = "考勤管理 >> 考勤统计";
                                break;
                        }
                        break;
                    }
                case "23":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                if (!string.IsNullOrEmpty(HttpContext.Current.Request["FeeKey"]))
                                    Title = "费用管理 >> 修改费用";
                                else
                                    Title = "费用管理 >> 添加费用";
                                break;
                            case "2":
                                Title = "费用管理 >> 费用管理";
                                break;
                            case "3":
                                Title = "费用管理 >> 费用统计";
                                break;
                        }
                        break;
                    }
            }
            //-------------------------员工管理End-------------------------

            //-------------------------物品与发票Begin-------------------------
            switch (MenuType.Substring(0, 2))
            {   
                case "31":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                if (!string.IsNullOrEmpty(HttpContext.Current.Request["InStockKey"]))
                                    Title = "入库管理 >> 修改入库单";
                                else
                                    Title = "入库管理 >> 添加入库单";
                                break;
                            case "2":
                                Title = "入库管理 >> 入库单管理";
                                break;
                        }
                        break;
                    }
                case "32":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                if (!string.IsNullOrEmpty(HttpContext.Current.Request["InStockKey"]))
                                    Title = "出库管理 >> 修改出库单";
                                else
                                    Title = "出库管理 >> 添加出库单";
                                break;
                            case "2":
                                Title = "出库管理 >> 出库单管理";
                                break;
                        }
                        break;
                    }
                case "33":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                if (!string.IsNullOrEmpty(HttpContext.Current.Request["InvoiceKey"]))
                                    Title = "发票管理 >> 修改发票";
                                else
                                    Title = "发票管理 >> 添加发票";
                                break;
                            case "2":
                                Title = "发票管理 >> 发票管理";
                                break;
                        }
                        break;
                    }
                case "35":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                if (!string.IsNullOrEmpty(HttpContext.Current.Request["StockKey"]))
                                    Title = "物品管理 >> 修改物品";
                                else
                                    Title = "物品管理 >> 添加物品";
                                break;
                            case "2":
                                Title = "物品管理 >> 物品管理";
                                break;
                        }
                        break;
                    }
                case "36":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                if (!string.IsNullOrEmpty(HttpContext.Current.Request["WxStockKey"]))
                                    Title = "报修物品管理 >> 物品入库修改";
                                else
                                    Title = "报修物品管理 >> 物品入库";
                                break;
                            case "2":
                                Title = "报修物品管理 >> 报修物品";
                                break;
                            case "3":
                                Title = "报修物品管理 >> 出库物品";
                                break;
                        }
                        break;
                    }
            }
            //-------------------------物品与发票End-------------------------

            //-------------------------客户关系Begin-------------------------
            switch (MenuType.Substring(0, 2))
            {
                case "41":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                if (!string.IsNullOrEmpty(HttpContext.Current.Request["InStockKey"]))
                                    Title = "客户档案 >> 添加客户档案";
                                else
                                    Title = "客户档案 >> 修改客户档案";
                                break;
                            case "2":
                                Title = "客户档案 >> 客户档案管理";
                                break;
                        }
                        break;
                    }
                case "42":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                if (!string.IsNullOrEmpty(HttpContext.Current.Request["ContractKey"]))
                                    Title = "合同管理 >> 修改合同";
                                else
                                    Title = "合同管理 >> 添加合同";
                                break;
                            case "2":
                                Title = "合同管理 >> 合同管理";
                                break;
                        }
                        break;
                    }
                case "43":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                Title = "客户投诉 >> 我要投诉";
                                break;
                            case "2":
                                Title = "客户投诉 >> 投诉管理";
                                break;
                        }
                        break;
                    }
                case "44":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                Title = "留言管理 >> 我要留言";
                                break;
                            case "2":
                                Title = "留言管理 >> 留言管理";
                                break;
                        }
                        break;
                    }
                case "45":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                Title = "通知管理 >> 发送消息";
                                break;
                            case "2":
                                Title = "通知管理 >> 已发送通知";
                                break;
                            case "3":
                                Title = "通知管理 >> 已接收通知";
                                break;
                        }
                        break;
                    }
                case "46":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                Title = "客户信息 >> 客户信息";
                                break;
                        }
                        break;
                    }
            }
            //-------------------------客户关系End-------------------------


            //-------------------------系统管理Begin-------------------------
            switch (MenuType.Substring(0, 2))
            {
                case "61":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                if (!string.IsNullOrEmpty(HttpContext.Current.Request["UserKey"]))
                                    Title = "用户管理 >> 修改用户";
                                else
                                    Title = "用户管理 >> 添加用户";
                                break;
                            case "2":
                                Title = "用户管理 >> 用户管理";
                                break;
                        }
                        break;
                    }
                case "62":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                Title = "权限管理 >> 权限管理";
                                break;
                        }
                        break;
                    }
                case "63":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                Title = "数据备份 >> 备份数据";
                                break;
                            case "2":
                                Title = "数据备份 >> 备份记录管理";
                                break;
                        }
                        break;
                    }
                case "64":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                Title = "数据恢复 >> 恢复数据";
                                break;
                            case "2":
                                Title = "数据恢复 >> 恢复记录管理";
                                break;
                        }
                        break;
                    }
                case "65":
                    {
                        switch (MenuType.Substring(2, 1))
                        {
                            case "1":
                                Title = "参数管理 >> 参数管理";
                                break;
                        }
                        break;
                    }
            }
            //-------------------------系统管理End-------------------------
            return Title;
        }

        //服务状态
        public static string GetTypeName(int Type)
        {
            string val = "";

            switch (Type)
            {
                case 1:
                    val = "任务已提交";
                    break;
                case 2:
                    val = "任务已分配";
                    break;
                case 3:
                    val = "技术员途中";
                    break;
                case 4:
                    val = "任务处理中";
                    break;
                case 5:
                    val = "任务未完成";
                    break;
                case 6:
                    val = "任务已完成";
                    break;
                default:
                    val = "";
                    break;
            }
            return val;
        }

        public static string GetStringByLen(string str,int len)
        {
            if (str.Trim().Length<=len)
                return str;
            else
                return str.Substring(0, len) + "...";
        }


        //删除所有已导出文件
        public static void DelExport()
        {
            string[] files = Directory.GetFiles(HttpContext.Current.Server.MapPath("~/export"));

            foreach(string f in files)
            {
                try
                {
                    File.Delete(f);
                }
                catch (Exception ex)
                { }
            }
        }
    }
}
